package xyz.lspace.newlrshk;


import android.util.Log;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public abstract class SocketServer implements Runnable {

    //端口
    private Integer port = null;

    public SocketServer(Integer port) {
        this.port = port;
    }

    @Override
    public void run() {
        Log.i("xp-------------:", "服务器开始启动");
        try {
            ServerSocket ss = new ServerSocket(port);
            Log.i("xp-------------:", "服务器启动中");

            while (true) {
                Socket s = ss.accept();
                BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                //读取客户端发送来的消息
                String mess = br.readLine();
                Log.i("xp-------------:", "客户端：" + mess);
                System.out.println("客户端：" + mess);
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                bw.write(execute(mess) + "\n");
                bw.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.i("xp-------------:", "服务器异常");
        }
    }

    //处理接收到的字符串
    public abstract String execute(String msg);

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }
}
